package com.meihuayishu.backend.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class JwtUtil {
    
    @Value("${jwt.secret:meihuayishu-secret-key-for-jwt-token-generation-2024}")
    private String secret;
    
    @Value("${jwt.access-token-expiration:7200}")
    private Long accessTokenExpiration; // 2小时，单位：秒
    
    @Value("${jwt.refresh-token-expiration:2592000}")
    private Long refreshTokenExpiration; // 30天，单位：秒
    
    private SecretKey getSigningKey() {
        byte[] keyBytes = secret.getBytes();
        return Keys.hmacShaKeyFor(keyBytes);
    }
    
    /**
     * 生成访问令牌
     */
    public String generateAccessToken(String userId, String phone, String membershipType) {
        return generateToken(userId, phone, membershipType, accessTokenExpiration, "access");
    }
    
    /**
     * 生成刷新令牌
     */
    public String generateRefreshToken(String userId) {
        return generateToken(userId, null, null, refreshTokenExpiration, "refresh");
    }
    
    /**
     * 生成令牌
     */
    private String generateToken(String userId, String phone, String membershipType, Long expiration, String tokenType) {
        Instant now = Instant.now();
        Instant expiryDate = now.plus(expiration, ChronoUnit.SECONDS);
        
        JwtBuilder builder = Jwts.builder()
                .subject(userId)
                .issuedAt(Date.from(now))
                .expiration(Date.from(expiryDate))
                .claim("tokenType", tokenType);
        
        if (phone != null) {
            builder.claim("phone", phone);
        }
        if (membershipType != null) {
            builder.claim("membershipType", membershipType);
        }
        
        return builder.signWith(getSigningKey()).compact();
    }
    
    /**
     * 从令牌中获取用户ID
     */
    public String getUserIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getSubject();
    }
    
    /**
     * 从令牌中获取手机号
     */
    public String getPhoneFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.get("phone", String.class);
    }
    
    /**
     * 从令牌中获取会员类型
     */
    public String getMembershipTypeFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.get("membershipType", String.class);
    }
    
    /**
     * 从令牌中获取所有声明
     */
    public Claims getClaimsFromToken(String token) {
        try {
            return Jwts.parser()
                    .verifyWith(getSigningKey())
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (JwtException e) {
            log.error("JWT解析失败: {}", e.getMessage());
            throw new IllegalArgumentException("无效的JWT令牌", e);
        }
    }
    
    /**
     * 验证令牌
     */
    public boolean validateToken(String token) {
        try {
            Jwts.parser()
                    .verifyWith(getSigningKey())
                    .build()
                    .parseSignedClaims(token);
            return true;
        } catch (JwtException | IllegalArgumentException e) {
            log.debug("JWT验证失败: {}", e.getMessage());
            return false;
        }
    }
    
    /**
     * 检查令牌是否过期
     */
    public boolean isTokenExpired(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }
    
    /**
     * 获取令牌剩余有效时间（秒）
     */
    public long getTokenRemainingTime(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            long remaining = (expiration.getTime() - System.currentTimeMillis()) / 1000;
            return Math.max(0, remaining);
        } catch (Exception e) {
            return 0;
        }
    }
    
    /**
     * 从Authorization头中提取Bearer令牌
     */
    public String extractTokenFromHeader(String authorizationHeader) {
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            return authorizationHeader.substring(7);
        }
        return null;
    }
}